﻿  using UnityEngine;
using System.Collections;

namespace Lost{
	///机关物品，即需要别的物品去触发的可交互物品
	public class DeviceItem : InteractiveItem {
		///需要的物品名
		[SerializeField] protected string itemNeeded;
		///交互后物品放哪？
		[SerializeField] protected Transform itemPos;
		///如果指定物品触发了，是否禁止DeviceItem的交互
		[SerializeField] protected bool disableDevice = false;
		///是否已经成功触发
		protected bool isFinished;
		///进入了触发器且名为ItemName的ItemTag
		ItemTag fitItem;

		///成功触发后的新介绍
		[SerializeField] protected string newIntroduction;
		///成功触发后的使能的物品
		[SerializeField] protected string[] itemsEnable;

		[SerializeField] float triggerRadius = 0.5f;
		SphereCollider newTrigger;
		Rigidbody newRigidbody;

		void Awake(){
			//添加触发器和刚体，如果有就不添加了
			Collider trigger = GetComponent<Collider> ();
			if (trigger == null || trigger.isTrigger == false) {
				newTrigger = gameObject.AddComponent<SphereCollider> ();
				newTrigger.isTrigger = true;
				newTrigger.radius = triggerRadius;
			}
			Rigidbody rb = GetComponent<Rigidbody> ();
			if (rb == null) {
				newRigidbody = gameObject.AddComponent<Rigidbody> ();
				newRigidbody.useGravity = false;
			}
		}

		void OnTriggerEnter(Collider col){
			Debug.Log ("Enter");
			ItemTag it = col.gameObject.GetComponent<ItemTag> ();
			Debug.Log (it);
			if (it != null && it.ItemName == itemNeeded) {
				Debug.Log ("Fit");
				fitItem = it;
			}
		}
		void OnTriggerExit(Collider col){
			ItemTag it = col.gameObject.GetComponent<ItemTag> ();
			if (it != null && it.ItemName == itemNeeded) {
				Debug.Log ("Exit");
				fitItem = null;
			}
		}

		public override void Interact (HitInf hitInf)
		{
			if (!IsInteractive) {
				return;
			}
			if (fitItem!=null) {
				isFinished = true;
				//GameObject itemHolding = BackpackInteraction.ItemHolding;
				GameObject itemHolding = fitItem.gameObject;
				GameObject colon = GameObject.Instantiate (itemHolding, itemPos.position, itemPos.rotation) as GameObject;
				colon.transform.localScale = itemHolding.transform.lossyScale;
				colon.transform.parent = itemPos;
				//去掉某些组件
				ItemTag colonIT = colon.GetComponent<ItemTag> ();
				if (colonIT != null) {
					Destroy (colonIT);
				}
				Rigidbody rb = colon.GetComponent<Rigidbody> ();
				if (rb != null) {
					Destroy (rb);
				}

				Introduction = newIntroduction;
				ItemsManager.iDestroy (fitItem.gameObject);
				if (newRigidbody != null) {
					Destroy (newRigidbody);
				}
				if (newTrigger != null) {
					Destroy (newTrigger);
				}
				BackpackInteraction.UseItem (fitItem.ItemName);
				foreach (string itemName in itemsEnable) {
					ItemTag it = ItemsManager.FindItemTag (itemName);
					if (it.isActiveAndEnabled == false) {
						it.gameObject.SetActive (true);
					}
					InteractiveItem ii = it.GetComponent<InteractiveItem> ();
					if (ii != null) {
						ii.SetInteractive (true);
					}
				}
			} else {
				Debug.Log (Introduction);
			}
		}
	}
}
